package com.ocom.mqsimple.business.human.impl;


import com.alibaba.fastjson.JSON;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.StringUtil;
import com.ocom.common.vo.PersonVo;
import com.ocom.mqsimple.business.human.HumanProductService;
import com.ocom.mqsimple.feign.MinioClientService;
import com.ocom.mqsimple.utils.HumanRabbitProductUitl;
import com.ocom.mqsimple.vo.SavePhotoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HumanProductServiceImpl implements HumanProductService {
	private final Logger log = LoggerFactory.getLogger(HumanProductServiceImpl.class);


	@Autowired
	private HumanRabbitProductUitl humanRabbitProductUitl;

	@Autowired
	private MinioClientService minioClientService;

	/**
	 * 处理人员图片
	 */
	@Transactional
	public void SavePhoto(SavePhotoVo savePhotoVo) {

		log.info("处理人员图片开始【{}】",savePhotoVo);
		//消息队列调用减库存接口  优先级越高越先执行完
		String[] strings = savePhotoVo.getPPhotoUrl().split("\\.");
		String images = "png,jpg,jpeg,bmp,gif,webp";
		String[] stringList = images.split(",");
		for (String image: stringList) {
			if (!image.equals(strings[strings.length-1])){
				continue;
			}
			log.info("image{{}}",image);
			log.info("strings[strings.length-1]:{{}}",strings[strings.length-1]);
			List<String> urls= new ArrayList<>();
			urls.add(savePhotoVo.getPPhotoUrl());
			Map<String ,Object> map = new HashMap<>();
			map.put("fileName","");
			map.put("urls",urls);
			HumanProductServiceImpl img=new HumanProductServiceImpl();
			log.info("map{{}}",map);
			String PathUrl = img.download(map);
			File file = new File(PathUrl);
//			if (!img.checkFileSize(file, 2, "M")){
//				doWithPhoto(PathUrl);
//			}
			Result upload = minioClientService.upload(file);
			log.info("图像上传:{{}}",upload);
			PersonVo personVo = new PersonVo();
			personVo.setComId(savePhotoVo.getComId());
			personVo.setPId(savePhotoVo.getPId());
			personVo.setPPhotoUrl((String) JSON.parseObject(JSON.toJSONString(upload.getData())).get("imageUrl"));
			log.info("发送消息开始personVo{{}}",personVo);
			String msg = JSON.toJSONString(personVo);
			humanRabbitProductUitl.humansend(msg,15);

			log.info("处理人员图片完成【{}】",msg);
		}




	}


	public String download(Map<String ,Object> map){

		List<String> urls = (List<String>) map.get("urls");
		String fileName = (String) map.get("fileName");
		String savePath = "images";
		for (String imgUrl : urls) {
			if (StringUtil.isEmpty(imgUrl)){
				continue;
			}
			log.info("imgUrl{{}}",imgUrl);
			try {
				fileName = imgUrl.substring(imgUrl.lastIndexOf("/"));
				log.info("savePath{{}}", savePath);
				// 构造URL
				URL url = new URL(imgUrl);
				// 打开连接
				URLConnection con = url.openConnection();
				con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
				//设置请求超时为5s
				con.setConnectTimeout(5*1000);
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				File sf=new File(String.valueOf(savePath));
				if(!sf.exists()){
					sf.mkdirs();
				}
				OutputStream os = new FileOutputStream(sf.getPath()+"/"+fileName);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();

			}catch (Exception e){
				log.error("异常{{}}",e.getMessage());
			}
		}
		log.info("fileName{{}}",fileName);
		log.info("===================end====================");
		return savePath +fileName;
	}

	private static byte[] readInputStream(InputStream inputStream) throws IOException {

		byte[] buffer = new byte[1024];
		int len;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * 判断文件大小
	 *
	 * @param file
	 *            文件
	 * @param size
	 *            限制大小
	 * @param unit
	 *            限制单位（B,K,M,G）
	 * @return
	 */
	public  boolean checkFileSize(File file, int size, String unit) {
		long len = file.length();
		double fileSize = 0;
		switch (unit.toUpperCase()) {
			case "B":
				fileSize = (double) len;
				break;
			case "K":
				fileSize = (double) len / 1024;
				break;
			case "M":
				fileSize = (double) len / 1048576;
				break;
			case "G":
				fileSize = (double) len / 1073741824;
				break;
		}
		log.info("fileSize{{}}",fileSize);
		return !(fileSize > size);
	}

//	/**
//	 * 对图片进行原比例无损压缩,压缩后覆盖原图片
//	 *
//	 */
//	private static void doWithPhoto(String path) {
//		File file = new File(path);
//		if (!file.exists()) {
//			return;
//		}
//		BufferedImage image;
//		FileOutputStream os = null;
//		try {
//			image = ImageIO.read(file);
//			int width = image.getWidth();
//			int height = image.getHeight();
//			BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//			bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
//			os = new FileOutputStream(path);
//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//			encoder.encode(bfImage);
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (os != null) {
//				try {
//					os.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}
}
